package com.smasher.bluetooth.connect;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;

import java.io.IOException;
import java.util.UUID;

public class ConnectClassic extends BaseConnect implements Handler.Callback {

    public static final String TAG = "ClassicConnect";

    private BluetoothSocket bluetoothSocket;
    private ConnectThread connectThread;

    private UUID serviceUuid = UUID.fromString("0000110A-0000-1000-8000-00805F9B34FB"); // SPP UUID

    public ConnectClassic(Context context) {
        super(context);
    }


    /**
     * 设置连接使用的 Service UUID（默认为 SPP）
     */
    public void setServiceUuid(UUID uuid) {
        this.serviceUuid = uuid;
    }


    /**
     * 连接经典蓝牙设备
     */
    @Override
    @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN})
    public void connectDevice(Context context,@NonNull BluetoothDevice device) {
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            Log.i(TAG, "未配对，准备配对");
            pairedDevice(device); // 触发配对流程
        } else {
            Log.i(TAG, "已配对，尝试连接");
            startConnectThread(device);
        }
    }

    @Override
    public void connectDeviceImmediately(Context context, BluetoothDevice device) {
        super.connectDeviceImmediately(context, device);
        startConnectThread(device);
    }

    /**
     * 启动连接线程
     */
    private void startConnectThread(BluetoothDevice device) {
        if (connectThread != null) {
            connectThread.cancel();
            connectThread = null;
        }
        connectThread = new ConnectThread(device);
        connectThread.start();
    }


    /**
     * 终止连接
     */
    public void disconnect() {
        if (connectThread != null) {
            connectThread.cancel();
            connectThread = null;
        }
        try {
            if (bluetoothSocket != null && bluetoothSocket.isConnected()) {
                bluetoothSocket.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "关闭 socket 失败", e);
        }
    }

    /**
     * 释放资源
     */
    public void release(Context context) {
        super.release(context);
        disconnect();
    }


    /**
     * 连接线程
     */
    private class ConnectThread extends Thread {

        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
        }

        @SuppressLint("MissingPermission")
        @Override
        public void run() {
            try {
                // 固定使用串口服务
                bluetoothSocket = (BluetoothSocket) mmDevice.getClass()
                        .getMethod("createRfcommSocketToServiceRecord", UUID.class)
                        .invoke(mmDevice, serviceUuid);

                bluetoothSocket.connect();

                if (connectionListener != null) {
                    connectionListener.onConnected(mmDevice);
                }

            } catch (Exception connectException) {
                Log.e(TAG, "连接失败: ", connectException);
                try {
                    bluetoothSocket.close();
                } catch (IOException closeException) {
                    Log.e(TAG, "无法关闭 socket", closeException);
                }
            }

            // 成功后可启动数据读写线程
        }

        public void cancel() {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭 socket 异常", e);
            }
        }
    }


    @Override
    public boolean handleMessage(@NonNull Message msg) {
        return false;
    }
}
